﻿using LunarSF.SHomeWorkshop.LunarMind;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace SHomeWorkshop.LunarMind.TestEditor
{
    /// <summary>
    /// QuestionEditorWindow.xaml 的交互逻辑
    /// </summary>
    public partial class QuestionEditorWindow : Window
    {
        public QuestionEditorWindow(Title title)
        {
            InitializeComponent();

            Grid.SetRow(mainEditor, 1);
            mainGrid.Children.Add(mainEditor);

            this.masterTitle = title;

            if (title == null)
            {
                this.mainEditor.Text = "出现异常：未传入要编辑后台试题文本的标题。不可编辑。";
                this.mainEditor.IsEnabled = false;
            }

            string srcText = XmlTools.RestoreXmlChars(title.QuestionText);
            if (string.IsNullOrEmpty(srcText))
            {
                this.mainEditor.Text = Properties.Resources.TitleBackgroundQuestionsSample;
            }
            else
            {
                this.mainEditor.Text = srcText;
            }
            this.mainEditor.Document.UndoStack.MarkAsOriginalFile();

            //启用快捷键。避免输入法干扰。
            Globals.SwitchInputMethod(false);

            this.Loaded += QuestionEditorWindow_Loaded;

            this.KeyDown += QuestionEditorWindow_KeyDown;
        }

        void QuestionEditorWindow_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.F2:
                    {
                        miWrapWithSquareBrackets_Click(sender, e);
                        break;
                    }
                case Key.F4:
                    {
                        miInsertChoiceQuestionTags_Click(sender, e);
                        break;
                    }
                case Key.F8:
                    {
                        miInsertJudgeQuestionTrueTags_Click(sender, e);
                        break;
                    }
                case Key.F9:
                    {
                        miInsertJudgeQuestionTagsFalse_Click(sender, e);
                        break;
                    }
            }
        }

        void QuestionEditorWindow_Loaded(object sender, RoutedEventArgs e)
        {
            mainEditor.Focus();
        }

        private Title masterTitle;

        public Title MasterTitle { get { return this.masterTitle; } }

        private QuestionEditor mainEditor = new QuestionEditor() { FontSize = 16, Margin = new Thickness(10), };

        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            this.UpdateToTitle();

            this.Close();
        }

        private void UpdateToTitle()
        {
            if (masterTitle == null)
            {
                MessageBox.Show("未传入有效的标题，无法编辑！", Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                this.Close();
                return;
            }

            ModifingItem mi = new ModifingItem()
            {
                ModifingName = "编辑标题的后台试题文本",
            };

            if (masterTitle.TextDock != Dock.Bottom)
            {
                string newQuestionText = XmlTools.ReplaceXmlChars(mainEditor.Text);

                Action actQuestionText = new Action(masterTitle.ID, -1, masterTitle.GetType().Name, "QuestionText",
                    masterTitle.QuestionText, newQuestionText);
                masterTitle.QuestionText = newQuestionText;
                mi.Add(actQuestionText);
            }

            if (mi.ModifiedPropertyAndValues.Count > 0)
            {
                Globals.MainWindow.Do(mi);
                Globals.MainWindow.IsModified = true;
            }

            this.mainEditor.Document.UndoStack.MarkAsOriginalFile();
        }

        private void miWrapWithSquareBrackets_Click(object sender, RoutedEventArgs e)
        {
            this.mainEditor.Document.Replace(this.mainEditor.SelectionStart, this.mainEditor.SelectedText.Length, "【" + this.mainEditor.SelectedText + "】");
            this.mainEditor.CaretOffset = this.mainEditor.SelectionStart + this.mainEditor.SelectionLength;

            if (this.mainEditor.SelectionLength > 2)
            {
                this.mainEditor.Select(this.mainEditor.CaretOffset, 0);//如果是将选定的字符括起来，不定位到括弧内
            }
            else
            {
                this.mainEditor.Select(this.mainEditor.CaretOffset - 1, 0);//如果只输出一对括弧，则直接在括弧中输入
            }
        }

        /// <summary>
        /// 尝试根据试题文本判断其中有几个填空项，然后根据这些填空项自动插入一些“答案＞＞”“错项＞＞”“解析＞＞”之类的标签。
        /// </summary>
        public void InsertChoiceQuestionTags()
        {
            //if (this.SelectionLength <= 0)
            //{
            //    SelectLine();
            //}

            //选择区域所在的行都选中
            var startLine = this.mainEditor.Document.GetLineByOffset(this.mainEditor.SelectionStart);
            var endLine = this.mainEditor.Document.GetLineByOffset(this.mainEditor.SelectionStart + this.mainEditor.SelectionLength);
            this.mainEditor.Select(startLine.Offset, endLine.EndOffset - startLine.Offset);

            //要求选中题干文本（全部）
            var text = this.mainEditor.SelectedText.Replace("\r\n", "").Replace("\t", "").Replace(" ", "").Replace("　", "");
            if (text.StartsWith("试题＞＞") == false)
            {
                MessageBox.Show("　　请选中要生成标签的试题文本，这些文本中应至少有一个用方括弧对标记出来的填充项。",
                    Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            int fillblankCount = 0;
            StringBuilder errorMsg = new StringBuilder();

            if (QuestionValidateManager.ValidatePairOfBrackets(text, ref fillblankCount, true, errorMsg, false) == false)//选择题必须提供答案。
            {
                MessageBox.Show("　　选中的文本格式存在问题，无法自动生成标签集。错误信息如下：\r\n" + errorMsg.ToString(),
                   Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            char[] splitterLeft = new char[1];
            splitterLeft[0] = '【';

            char[] splitterRight = new char[1];
            splitterRight[0] = '】';

            string[] arrayLeft = text.Split(splitterLeft, StringSplitOptions.RemoveEmptyEntries);

            List<string> answers = new List<string>();

            foreach (string s in arrayLeft)
            {
                if (s.Contains("】") == false) continue;

                int index = s.IndexOf('】');
                if (index < 0) continue;

                string answer = s.Substring(0, index);
                answers.Add(answer);
            }

            StringBuilder tagsText = new StringBuilder();

            int fstAnswerLength = -1;

            tagsText.Append("\r\n\t\t\t\r\n");
            foreach (var s in answers)
            {
                if (fstAnswerLength < 0)
                {
                    fstAnswerLength = s.Length;
                }

                tagsText.Append("　　答案＞＞" + s + "\r\n");
                tagsText.Append("　　解析＞＞\r\n\t\t\t\r\n");

                //默认三个错项。
                tagsText.Append("　　错项＞＞\r\n");
                tagsText.Append("　　解析＞＞\r\n\t\t\t\r\n");
                tagsText.Append("　　错项＞＞\r\n");
                tagsText.Append("　　解析＞＞\r\n\t\t\t\r\n");
                tagsText.Append("　　错项＞＞\r\n");
                tagsText.Append("　　解析＞＞\r\n\t\t\t\r\n");
            }
            tagsText.Append("〓〓〓〓〓〓\r\n\r\n");//空一行，顶格，方便立即开始编辑新试题

            var line = this.mainEditor.Document.GetLineByOffset(this.mainEditor.SelectionStart + this.mainEditor.SelectionLength - 1);//这个长度肯定大于0。

            int oldEndOffset = line.EndOffset;

            this.mainEditor.Document.Insert(line.EndOffset, tagsText.ToString());
            this.mainEditor.Select(oldEndOffset + fstAnswerLength + 34, 0);
        }

        private void miInsertChoiceQuestionTags_Click(object sender, RoutedEventArgs e)
        {
            InsertChoiceQuestionTags();
        }

        internal void InsertJudgeQuestionTags(string judgeValue = "正确")
        {
            //选择区域所在的行都选中
            var startLine = this.mainEditor.Document.GetLineByOffset(this.mainEditor.SelectionStart);
            var endLine = this.mainEditor.Document.GetLineByOffset(this.mainEditor.SelectionStart + this.mainEditor.SelectionLength);
            this.mainEditor.Select(startLine.Offset, endLine.EndOffset - startLine.Offset);

            //要求选中题干文本（全部）
            var text = this.mainEditor.SelectedText.Replace("\r\n", "").Replace("\t", "").Replace(" ", "").Replace("　", "");
            if (text.StartsWith("试题＞＞") == false || text.Contains("【") == true || text.Contains("】") == true)
            {
                MessageBox.Show("　　请选中要生成标签的试题文本，这些文本中不应包括方括弧【和】，因为方括弧对包括的文本会被当成填充项。",
                    Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (text.Contains("【") || text.Contains("】"))
            {
                MessageBox.Show("　　选中的文本格式存在问题，无法自动生成判断题标签集。错误信息如下：\r\n" +
                    "判断题题干中不应包括方括号【和】，被方括号包围的文本会被当成填空项来处理。",
                    Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            //在末尾加上【正确】或【错误】。
            text += "【" + judgeValue + "】";

            char[] splitterLeft = new char[1];
            splitterLeft[0] = '【';

            char[] splitterRight = new char[1];
            splitterRight[0] = '】';

            string[] arrayLeft = text.Split(splitterLeft, StringSplitOptions.RemoveEmptyEntries);

            List<string> answers = new List<string>();

            foreach (string s in arrayLeft)
            {
                if (s.Contains("】") == false) continue;

                int index = s.IndexOf('】');
                if (index < 0) continue;

                string answer = s.Substring(0, index);
                answers.Add(answer);
            }

            StringBuilder tagsText = new StringBuilder();

            int fstAnswerLength = -1;

            tagsText.Append("【" + judgeValue + "】\r\n\t\t\t\r\n");
            foreach (var s in answers)
            {
                if (fstAnswerLength < 0)
                {
                    fstAnswerLength = s.Length;
                }

                tagsText.Append("　　答案＞＞" + judgeValue + "\r\n");
                tagsText.Append("　　解析＞＞\r\n\t\t\t\r\n");

                //默认三个错项。
                tagsText.Append("　　错项＞＞" + (judgeValue == "正确" ? "错误" : "正确") + "\r\n");
                tagsText.Append("　　解析＞＞\r\n\t\t\t\r\n");
            }
            tagsText.Append("〓〓〓〓〓〓\r\n\r\n");//空一行，顶格，方便立即开始编辑新试题

            var line = this.mainEditor.Document.GetLineByOffset(this.mainEditor.SelectionStart + this.mainEditor.SelectionLength - 1);//这个长度肯定大于0。

            int oldEndOffset = line.EndOffset;

            this.mainEditor.Document.Insert(line.EndOffset, tagsText.ToString());
            this.mainEditor.Select(oldEndOffset + fstAnswerLength + 25, 0);
        }

        private void miInsertJudgeQuestionTrueTags_Click(object sender, RoutedEventArgs e)
        {
            InsertJudgeQuestionTags("正确");
        }

        private void miInsertJudgeQuestionTagsFalse_Click(object sender, RoutedEventArgs e)
        {
            InsertJudgeQuestionTags("错误");
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.mainEditor.IsModified)
            {
                var result = MessageBox.Show("　　试题文本已修改，要写入到对应标题中吗？", Globals.AppName, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);
                switch (result)
                {
                    case MessageBoxResult.Yes:
                        {
                            UpdateToTitle();
                            break;
                        }
                    case MessageBoxResult.Cancel:
                        {
                            e.Cancel = true;
                            break;
                        }
                        //default://No，直接关闭窗口。放弃编辑的内容。
                }
            }
        }

    }
}
